package cn.xyinping.basic.util;

import cn.xyinping.user.domain.Logininfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取登陆用户的信息
 * 工具类不能加注解
 * @author 27266
 * @desrciption
 * @date 2021/11/2
 */
public class LoginContextUtil {
    public static Logininfo getLoginContext() {
        //请求: RequestContextHolder是SpringMVC中的一个请求上下文工具，里面有ServletRequestAttributes
        //而：ServletRequestAttributes里面有请求对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //拿到请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        return getLoginContext(request);
    }
        public static Logininfo getLoginContext (HttpServletRequest request){
            // 获取token（令牌）
            String token = request.getHeader("token");

            if (!StringUtils.isEmpty(token)) {
                // 不能通过注解获取redisTemplate，要从spring容器中获取redisTemplate
                //  获取spring容器
                WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

                //  再从容器中获取bean
                RedisTemplate redisTemplate = (RedisTemplate) applicationContext.getBean("redisTemplate");

                Object obj = redisTemplate.opsForValue().get(token);
                if (obj != null) {
                    return (Logininfo) obj;
                }
            }
            return null;
        }

}
